/* Shared library add-on to iptables to add string matching support. 
 * 
 * Copyright (C) 2000 Emmanuel Roger  <winfield@freegates.be>
 *
 * ChangeLog
 *     27.01.2001: Gianni Tedesco <gianni@ecsc.co.uk>
 *             Changed --tos to --string in save(). Also
 *             updated to work with slightly modified
 *             ipt_string_info.
 */
#include <stdio.h>
#include <netdb.h>
#include <string.h>
#include <stdlib.h>
#include <getopt.h>
#include <ctype.h>

#include <iptables.h>
#include "ipt_string.h"

static void print_string(char string[], int invert, int match, int numeric);

/* Function which prints out usage message. */
static void
help(void)
{
	printf(
"STRING match v%s options:\n"
"--string [!] string             Match a string in a packet\n",
NETFILTER_VERSION);

	fputc('\n', stdout);
}

static struct option opts[] = {
	{ "string", 1, 0, '1' },
	{0}
};

/* Initialize the match. */
static void
init(struct ipt_entry_match *m, unsigned int *nfcache)
{
	*nfcache |= NFC_UNKNOWN;
}

static int nibble(char what)
{
	if (isdigit((int)what)) return what - '0';
	if (isxdigit((int)what)) return toupper((int)what) - 'A' + 10;
	return -1;
}

static void
parse_string(const unsigned char *s, struct ipt_string_info *info)
{	
	int last,next,nextnext,p,pnext,len,lastlen;
	//unsigned char *cur;
	unsigned char buf[BM_MAX_NLEN*2];
	unsigned char *index, *url, *end;

        //if (strlen(s) < BM_MAX_NLEN-1){

		if(strlen(s)<2)
			exit_error(PARAMETER_PROBLEM, "Match method needed");

		if(s[0]=='0') info->match=0;
		else if(s[0]=='1') info->match=1;
		else if(s[0]=='2') info->match=2;
		else
			exit_error(PARAMETER_PROBLEM, "Invalid match method `%c'", s[0]);
		
		// decode URL and make up the chain
		strcpy(buf+1,s+2); // s start with: ? real url, ? -match method
		strcat(buf+1," ");
		last=0;

                index=url=buf+1;
                end = buf+1 + strlen(buf+1);

                while (index < end)
                {
                    if ((*index == '%') && (index < end - 2))
                    {
                        if (isxdigit((int)*(index+1)) && isxdigit((int)*(index+2)))
                        {
                            *url = (nibble(*(index+1)) << 4) | nibble(*(index+2));
                            index += 3; 
                            url++;
                        }
                        else
                        {
                            *url = *index;
                            url++;
                            index++;
                        }        
                    }
                    else if(*index==' ')
                    {
		        buf[last]=url-buf;
		        last=buf[last];
                        url++;
                        index++;
                    }
                    else
                    {
                        *url = *index;
                        url++;
                        index++;
                    }
                }
		buf[last]=0;
		if(strlen(buf) > BM_MAX_NLEN-1)
			exit_error(PARAMETER_PROBLEM, "STRING too long.");
		strcpy(info->string,buf);

		// sort the strings, using method of BUBBLE
		last=0;
		while(info->string[last]!=0)
		{
			lastlen=info->string[last]-last;
			next=info->string[last];
			while(info->string[next]!=0)
			{
				len=info->string[next]-next;
				if(len<lastlen)
				{
					// swap the string last and next point to
					// modify the pointers
					nextnext=info->string[next];
					info->string[next]=info->string[last]+len-lastlen;
					p=last;
					while(p<next)
					{
						pnext=info->string[p];
						info->string[p]+=len;
						p=pnext;
					}
					bzero(buf,sizeof(buf));
					strncpy(buf,info->string+next,len);
					strncat(buf,info->string+last,next-last);
					memcpy(info->string+last,buf,strlen(buf));
					lastlen=info->string[last]-last;
					next=nextnext;
				}
				else next=info->string[next];
			}
			last=info->string[last];
		}
	/*
	}
	else
		exit_error(PARAMETER_PROBLEM, "STRING too long `%s'", s);
	*/
}

/* Function which parses command options; returns true if it
   ate an option */
static int
parse(int c, char **argv, int invert, unsigned int *flags,
      const struct ipt_entry *entry,
      unsigned int *nfcache,
      struct ipt_entry_match **match)
{
	struct ipt_string_info *stringinfo = (struct ipt_string_info *)(*match)->data;

	switch (c) {
	case '1':
		if (check_inverse(optarg, &invert, NULL, 0))
			optind++;
		parse_string(argv[optind-1], stringinfo);
		if (invert)
			stringinfo->invert = 1;
                stringinfo->len=strlen((char *)&stringinfo->string);
		*flags = 1;
		break;

	default:
		return 0;
	}
	return 1;
}

/* Final check; must have specified --string. */
static void
final_check(unsigned int flags)
{
	if (!flags)
		exit_error(PARAMETER_PROBLEM,
			   "STRING match: You must specify `--string'");
}

static void
print_string(char string[], int invert, int match, int numeric)
{
	int i,cur;
	
	if(match==0) printf("MATCH begin ");
	else if(match==1) printf("MATCH include ");
	else if(match==2) printf("MATCH end ");

	if (invert)
		fputc('!', stdout);
	i=0;
	while((cur=string[i])!=0){
		string[i]=' ';
		i=cur;
	}
	printf("%s ",string);
		
}

/* Prints out the matchinfo. */
static void
print(const struct ipt_ip *ip,
      const struct ipt_entry_match *match,
      int numeric)
{
	printf("STRING match ");
	print_string(((struct ipt_string_info *)match->data)->string,
		  ((struct ipt_string_info *)match->data)->invert, 
		  ((struct ipt_string_info *)match->data)->match,
		  numeric);
}

/* Saves the union ipt_matchinfo in parsable form to stdout. */
static void
save(const struct ipt_ip *ip, const struct ipt_entry_match *match)
{
	printf("--string ");
	print_string(((struct ipt_string_info *)match->data)->string,
		  ((struct ipt_string_info *)match->data)->invert, 
		  ((struct ipt_string_info *)match->data)->match, 
		  0);
}

static
struct iptables_match string
= { NULL,
    "string",
    NETFILTER_VERSION,
    IPT_ALIGN(sizeof(struct ipt_string_info)),
    IPT_ALIGN(sizeof(struct ipt_string_info)),
    &help,
    &init,
    &parse,
    &final_check,
    &print,
    &save,
    opts
};

void _init(void)
{
	register_match(&string);
}
